package com.xin.data.simbapesa.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.adapter.AccountAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaAccountActivityBinding;
import com.xin.data.simbapesa.dialog.DeleteDialog;
import com.xin.data.simbapesa.dialog.MoreDialog;
import com.xin.data.simbapesa.dialog.SameDialog;
import com.xin.data.simbapesa.dialog.SubmitDialog;
import com.xin.data.simbapesa.obj.SimbaAccountItem;
import com.xin.data.simbapesa.obj.SimbaWalletChannel;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.OrderUtils;
import com.xin.data.simbapesa.utils.PopUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.Tools;
import com.xin.data.simbapesa.utils.ViewUtils;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SimbaAccountActivity extends BaseActivity<SimbaAccountActivityBinding> {


    final String stepTag = "ACCOUNTINFO";

    List<SimbaAccountItem> dataList;
    AccountAdapter adater;

    MoreDialog moreCardDialog;

    SameDialog sameCardDialog;

    SubmitDialog submitCardDialog;

    DeleteDialog deleteCardDialog;


    @Override
    protected SimbaAccountActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaAccountActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.getRoot().setPadding(0, 0, 0, 0);
        setStatusBarHeight2(binding.tvRoot, ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12));

        dataList = new ArrayList<>();
        adater = new AccountAdapter(dataList);
        adater.setEdit(true);
        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager1);
        int d1 = ResUtils.d(R.dimen.dp_6);
        binding.recyclerView.addItemDecoration(new SimbaSpaceItemDecoration(d1, d1, getActivity()));
        adater.setOnBtnItemClickListener(position -> {
            SimbaAccountItem item = dataList.get(position);
            if (item.isData()) {
                showDeleteCardDialog(item);
            } else {
                addCardPop();
            }
        });
        binding.recyclerView.setAdapter(adater);
        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P83, "");
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
        });
        binding.tvBtn.setOnClickListener(v -> {
            if (binding.tvBtn.isSelected()) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P84, "");
                PU.userBuriedAllPoint(getActivity());
                toNext();
            }
        });
        binding.getRoot().setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot()));
        binding.tvAdd.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P28 + stepTag + "_ADD_CLICK", "");
            addCardPop();
        });

        binding.tvBtn.setSelected(false);

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P81;
        UP_TYPE2 = PU.P82;


        loadData(null);

        fetchBoundBankAccount();
    }


    void loadData(List<SimbaAccountItem> list) {

        if (getActivity() != null && !isFinishing()) {
            dataList.clear();
            if (list != null && !list.isEmpty()) {
                binding.tvBtn.setSelected(true);
                dataList.addAll(list);
                if (list.size() == 1) {
                    SimbaAccountItem cardInfo1 = new SimbaAccountItem();
                    cardInfo1.setData(false);
                    cardInfo1.setShowName(false);
                    dataList.add(cardInfo1);
                }
            } else {
                binding.tvBtn.setSelected(false);
                SimbaAccountItem cardInfo1 = new SimbaAccountItem();
                cardInfo1.setData(false);
                cardInfo1.setShowName(false);
                SimbaAccountItem cardInfo2 = new SimbaAccountItem();
                cardInfo2.setData(false);
                cardInfo2.setShowName(false);
                dataList.add(cardInfo1);
                dataList.add(cardInfo2);
            }
            for (SimbaAccountItem item : dataList) {
                item.setShowName(true);
            }
            adater.updateAllData();
        }
    }

    void fetchBoundBankAccount() {
        showLoading("");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[22]);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-fetchBoundBankAccount post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "fetchBoundBankAccount json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                List<SimbaAccountItem> list = JsonParse.fetchBoundBankAccountJson2Obj(json1);
                                if (list != null) {
                                    for (SimbaAccountItem item : list) {
                                        if (U.isCameroon) {
                                            if (item.getWalletDesc().equals("MTN")) {
                                                item.setWalletLogo("https://divoire.s3.af-south-1.amazonaws.com/pic/33149e4bbeb2466dac7665034f9e84e6.jpg");
                                            }
                                            if (item.getWalletDesc().equals("Orange Money")||item.getWalletDesc().equals("ORANGE")) {
                                                item.setWalletLogo("https://divoire.s3.af-south-1.amazonaws.com/app/Orangemoneylogo.png");
                                            }
                                        }
                                    }
                                }
                                loadData(list);
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                        if (e != null) {
                            LogUtil.e("me", "fetchBoundBankAccount e->" + e);
                        }
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    void addCardPop() {
        if (SimbaApp.getInstance().getAppInfo() != null) {
            List<SimbaWalletChannel> walletChannelInfos = SimbaApp.getInstance().getAppInfo().getWalletChannels();
            if (walletChannelInfos != null) {
                showBindCardDialog(walletChannelInfos);
            }
        }
    }

    void showBindCardDialog(List<SimbaWalletChannel> list) {
        long clickStartTime = System.currentTimeMillis();
        PopUtils.showBindCardPop(getActivity(), binding.recyclerView, list, list.size(), new PopUtils.PopClickInterface2() {
            @Override
            public void onClickListener(SimbaWalletChannel info, String data) {
                if (!TextUtils.isEmpty(data) && info != null) {
                    long clickEndTime = System.currentTimeMillis();
                    PU.userBuriedPoint(PU.P87, data + "$$" + (clickEndTime - clickStartTime));
                    bindBankAccount(data, "NO", info);
                }
            }
        });
    }

    int getDataCout() {
        int cout = 0;
        for (SimbaAccountItem item : dataList) {
            if (item.isData()) {
                cout = cout + 1;
            }
        }
        return cout;
    }

    void bindBankAccount(String phone, String addBindFlag, SimbaWalletChannel info) {
        showLoading("");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[23]);
        json.addProperty("walletMobile", phone);
        json.addProperty("walletMobileConfirm", phone);
        json.addProperty("walletChannel", info.getValue());
        json.addProperty("addBindFlag", addBindFlag);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        LogUtil.e("me", "<-walletChannel->" + json);
        RxHttp.post(U.commonUrl, AESCryptUtilJar.encryptDefault(json.toString()), heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "bindBankAccount json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                String channel = JsonParse.bindBankAccountJson2Obj(json1);
                                if (!TextUtils.isEmpty(channel)) {
                                    showSameCardDialog(info, phone, channel);
                                } else {
                                    fetchBoundBankAccount();
                                }
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                        if (e != null) {
                            LogUtil.e("me", "bindBankAccount e->" + e);
                        }
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    void deleteBoundBankAccount(SimbaAccountItem info) {
        showLoading("");
        LogUtil.e("me", "--deleteBoundBankAccount--" + info.getId());
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[24]);
        json.addProperty("ids", info.getId());
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        RxHttp.post(U.commonUrl, AESCryptUtilJar.encryptDefault(json.toString()), heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "deleteBoundBankAccount json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                fetchBoundBankAccount();
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    void showDeleteCardDialog(SimbaAccountItem info) {
        if (deleteCardDialog == null) {
            deleteCardDialog = new DeleteDialog(this);
        }
        info.setClickStartTime(System.currentTimeMillis());
        deleteCardDialog.setIcon(info.getWalletLogo());
        deleteCardDialog.setTitle(info.getWalletDesc());
        deleteCardDialog.setSubTitle(info.getWalletMobile());
        deleteCardDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                info.setClickEndTime(System.currentTimeMillis());
                PU.userBuriedPoint(PU.P86, info.getWalletMobile() + "$$" + (info.getClickEndTime() - info.getClickStartTime()));
                deleteBoundBankAccount(info);
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
        deleteCardDialog.show();
    }

    void showSameCardDialog(SimbaWalletChannel info, String phone, String channel) {
        if (sameCardDialog == null) {
            sameCardDialog = new SameDialog(this);
        }
        long clickStartTime = System.currentTimeMillis();
        int cout = getDataCout();
        info.setValue(channel);
        sameCardDialog.setIcon(info.getLogo());
        sameCardDialog.setTitle(info.getDesc());
        sameCardDialog.setSubTitle(phone);
        sameCardDialog.setCout(cout);
        sameCardDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                long clickEndTime = System.currentTimeMillis();
                PU.userBuriedPoint(PU.P87, phone + "$$" + (clickEndTime - clickStartTime));
                bindBankAccount(phone, "YES", info);
            }

            @Override
            public void btnOnClickCancel() {
                PU.userBuriedPoint(PU.P95, "");
            }

            @Override
            public void btnOnClickColse() {
                PU.userBuriedPoint(PU.P95, "");
            }
        });
        sameCardDialog.show();
        PU.userBuriedPoint(PU.P94, "");
    }

    void showSubmitCardDialog() {
        if (submitCardDialog == null) {
            submitCardDialog = new SubmitDialog(this);
        }
        submitCardDialog.setData(dataList);
        submitCardDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                PU.userBuriedPoint(PU.P97, "");
                userProcess(() -> {
                    boolean isCheckSteps = checkSteps();
                    if (!isCheckSteps) {
                        int state = OrderUtils.getOrderStatus();
                        if (state <= 0) {
                            startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                        }
                    }
                    finish();
                }, true);
            }

            @Override
            public void btnOnClickCancel() {
                PU.userBuriedPoint(PU.P97, "");

            }

            @Override
            public void btnOnClickColse() {
                PU.userBuriedPoint(PU.P97, "");
            }
        });
        submitCardDialog.show();
        PU.userBuriedPoint(PU.P96, "");
    }

    void showMoreCardDialog() {
        if (moreCardDialog == null) {
            moreCardDialog = new MoreDialog(this);
        }
        moreCardDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                addCardPop();
                PU.userBuriedPoint(PU.P93, "");
            }

            @Override
            public void btnOnClickCancel() {
                PU.userBuriedPoint(PU.P93, "");
                userProcess(() -> {
                    boolean isCheckSteps = checkSteps();
                    if (!isCheckSteps) {
                        int state = OrderUtils.getOrderStatus();
                        if (state <= 0) {
                            startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                        }
                    }
                    finish();
                }, true);
            }

            @Override
            public void btnOnClickColse() {
                PU.userBuriedPoint(PU.P93, "");
            }
        });
        moreCardDialog.show();
        PU.userBuriedPoint(PU.P92, "");
    }

    void toNext() {
        int cout = 0;
        for (int i = 0; i < dataList.size(); i++) {
            SimbaAccountItem data = dataList.get(i);
            if (data.isData()) {
                cout = cout + 1;
            }
        }
        if (cout < 2) {
            showMoreCardDialog();
        } else {
            showSubmitCardDialog();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (deleteCardDialog != null) {
            deleteCardDialog.dismiss();
        }
        if (sameCardDialog != null) {
            sameCardDialog.dismiss();
        }
        if (moreCardDialog != null) {
            moreCardDialog.dismiss();
        }
        if (submitCardDialog != null) {
            submitCardDialog.dismiss();
        }
    }


}
